<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>线路管理 - 列车车次管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../css/admin.css" rel="stylesheet">
</head>
<body>
    <!-- 导航栏 -->    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="/admin/dashboard.html">
                <img src="/images/logo.jpeg" alt="Logo" class="admin-logo d-inline-block align-text-top">
                <i class="fas fa-train me-2"></i>列车车次管理系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/dashboard.html">
                            <i class="fas fa-tachometer-alt me-1"></i>仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/users.html">
                            <i class="fas fa-users me-1"></i>用户管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/stations.html">
                            <i class="fas fa-map-marker-alt me-1"></i>车站管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/trains.html">
                            <i class="fas fa-train me-1"></i>火车管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/admin/routes.html">
                            <i class="fas fa-route me-1"></i>线路管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/schedules.html">
                            <i class="fas fa-calendar-alt me-1"></i>班次管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/admin/tickets.html">
                            <i class="fas fa-ticket-alt me-1"></i>票务管理
                        </a>
                    </li>
                </ul>
                <ul class="navbar-nav">
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user me-1"></i><span id="adminName">管理员</span>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="/profile.html">个人资料</a></li>
                            <li><hr class="dropdown-divider"></li>
                            <li><a class="dropdown-item" href="#" onclick="logout()">退出登录</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container-fluid mt-4">
        <div class="row">
            <div class="col-12">
                <!-- 页面标题 -->
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h2><i class="fas fa-route me-2"></i>线路管理</h2>
                    <div>
                        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#routeModal" onclick="showAddRouteModal()">
                            <i class="fas fa-plus me-1"></i>添加线路
                        </button>
                        <button class="btn btn-success" onclick="exportToCSV()">
                            <i class="fas fa-download me-1"></i>导出数据
                        </button>
                    </div>
                </div>

                <!-- 搜索和过滤器 -->
                <div class="card mb-4">
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3">
                                <label for="searchRouteName" class="form-label">线路名称</label>
                                <input type="text" class="form-control" id="searchRouteName" placeholder="输入线路名称">
                            </div>
                            <div class="col-md-3">
                                <label for="searchStartStation" class="form-label">起始站</label>
                                <input type="text" class="form-control" id="searchStartStation" placeholder="输入起始站">
                            </div>
                            <div class="col-md-3">
                                <label for="searchEndStation" class="form-label">终点站</label>
                                <input type="text" class="form-control" id="searchEndStation" placeholder="输入终点站">
                            </div>
                            <div class="col-md-3 d-flex align-items-end">
                                <button class="btn btn-primary me-2" onclick="searchRoutes()">
                                    <i class="fas fa-search me-1"></i>搜索
                                </button>
                                <button class="btn btn-secondary" onclick="resetFilters()">
                                    <i class="fas fa-undo me-1"></i>重置
                                </button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 线路列表 -->
                <div class="card">
                    <div class="card-body">
                        <div id="loadingSpinner" class="text-center" style="display: none;">
                            <div class="spinner-border" role="status">
                                <span class="visually-hidden">加载中...</span>
                            </div>
                        </div>
                        
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead class="table-dark">
                                    <tr>
                                        <th>线路名称</th>
                                        <th>起始站</th>
                                        <th>终点站</th>
                                        <th>总距离</th>
                                        <th>预计时长</th>
                                        <th>经停站数</th>
                                        <th>状态</th>
                                        <th>创建时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="routesTableBody">
                                    <!-- 数据将通过JavaScript动态加载 -->
                                </tbody>
                            </table>
                        </div>

                        <!-- 分页 -->
                        <nav aria-label="分页导航">
                            <ul class="pagination justify-content-center" id="pagination">
                                <!-- 分页按钮将通过JavaScript动态生成 -->
                            </ul>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 添加/编辑线路模态框 -->
    <div class="modal fade" id="routeModal" tabindex="-1" aria-labelledby="routeModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="routeModalLabel">添加线路</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="routeForm">
                        <input type="hidden" id="routeId">
                        
                        <!-- 基本信息 -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="routeName" class="form-label">线路名称 <span class="text-danger">*</span></label>
                                    <input type="text" class="form-control" id="routeName" required>
                                    <div class="form-text">例如：京沪高铁、京广铁路</div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label for="totalDistance" class="form-label">总距离(公里)</label>
                                    <input type="number" class="form-control" id="totalDistance" min="0" step="0.1">
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="mb-3">
                                    <label for="estimatedDuration" class="form-label">预计时长(分钟)</label>
                                    <input type="number" class="form-control" id="estimatedDuration" min="0">
                                </div>
                            </div>
                        </div>

                        <!-- 起点和终点 -->
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="startStation" class="form-label">起始站 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="startStation" required>
                                        <option value="">请选择起始站</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="endStation" class="form-label">终点站 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="endStation" required>
                                        <option value="">请选择终点站</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <!-- 经停站管理 -->
                        <div class="mb-3">
                            <label class="form-label">经停站</label>
                            <div class="border rounded p-3">
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <select class="form-select" id="stationSelect">
                                            <option value="">选择经停站</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <input type="number" class="form-control" id="stationOrder" placeholder="站序" min="1">
                                    </div>
                                    <div class="col-md-3">
                                        <input type="number" class="form-control" id="stationDistance" placeholder="距离(公里)" min="0" step="0.1">
                                    </div>
                                    <div class="col-md-2">
                                        <button type="button" class="btn btn-primary" onclick="addStation()">
                                            <i class="fas fa-plus"></i> 添加
                                        </button>
                                    </div>
                                </div>
                                
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <thead>
                                            <tr>
                                                <th>站序</th>
                                                <th>车站</th>
                                                <th>距离(公里)</th>
                                                <th>操作</th>
                                            </tr>
                                        </thead>
                                        <tbody id="stationsTableBody">
                                            <!-- 经停站列表 -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="routeStatus" class="form-label">状态</label>
                            <select class="form-select" id="routeStatus">
                                <option value="正常">正常</option>
                                <option value="停运">停运</option>
                                <option value="维修">维修</option>
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" onclick="saveRoute()">
                        <i class="fas fa-save me-1"></i>保存
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 线路详情模态框 -->
    <div class="modal fade" id="routeDetailModal" tabindex="-1" aria-labelledby="routeDetailModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="routeDetailModalLabel">线路详情</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="routeDetailContent">
                    <!-- 详情内容将通过JavaScript动态生成 -->
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 删除确认模态框 -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel">确认删除</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <p>您确定要删除线路 <strong id="deleteRouteName"></strong> 吗？</p>
                    <p class="text-danger">此操作会同时删除该线路的所有班次，且不可撤销！</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" onclick="confirmDelete()">
                        <i class="fas fa-trash me-1"></i>删除
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="../js/admin.js"></script>
    <script>
        let currentPage = 1;
        let totalPages = 1;
        let deleteRouteId = null;
        let stations = [];
        let routeStations = [];

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            checkAdminAuth();
            loadStations();
            loadRoutes();
        });

        // 加载车站列表
        async function loadStations() {
            try {
                const response = await fetch('/api/stations', {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载车站列表失败');
                }
                
                stations = await response.json();
                
                // 填充车站选择器
                const startStationSelect = document.getElementById('startStation');
                const endStationSelect = document.getElementById('endStation');
                const stationSelect = document.getElementById('stationSelect');
                
                const stationOptions = stations.map(station => 
                    `<option value="${station.id}">${station.stationName} (${station.stationCode})</option>`
                ).join('');
                
                startStationSelect.innerHTML = '<option value="">请选择起始站</option>' + stationOptions;
                endStationSelect.innerHTML = '<option value="">请选择终点站</option>' + stationOptions;
                stationSelect.innerHTML = '<option value="">选择经停站</option>' + stationOptions;
                
            } catch (error) {
                console.error('加载车站列表失败:', error);
                showAlert('加载车站列表失败', 'danger');
            }
        }

        // 加载线路列表
        async function loadRoutes(page = 1) {
            try {
                showLoading(true);
                const searchRouteName = document.getElementById('searchRouteName').value;
                const searchStartStation = document.getElementById('searchStartStation').value;
                const searchEndStation = document.getElementById('searchEndStation').value;

                let url = `/api/routes?page=${page - 1}&size=10`;
                
                if (searchRouteName) {
                    url += `&routeName=${encodeURIComponent(searchRouteName)}`;
                }
                if (searchStartStation) {
                    url += `&startStation=${encodeURIComponent(searchStartStation)}`;
                }
                if (searchEndStation) {
                    url += `&endStation=${encodeURIComponent(searchEndStation)}`;
                }

                const response = await fetch(url, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('加载线路列表失败');
                }
                
                const data = await response.json();
                displayRoutes(data.content || data);
                
                if (data.totalPages) {
                    totalPages = data.totalPages;
                    currentPage = page;
                    updatePagination();
                }
            } catch (error) {
                console.error('加载线路列表失败:', error);
                showAlert('加载线路列表失败', 'danger');
            } finally {
                showLoading(false);
            }
        }

        // 显示线路列表
        function displayRoutes(routes) {
            const tbody = document.getElementById('routesTableBody');
            
            if (!routes || routes.length === 0) {
                tbody.innerHTML = '<tr><td colspan="9" class="text-center">暂无数据</td></tr>';
                return;
            }

            tbody.innerHTML = routes.map(route => `
                <tr>
                    <td>
                        <strong>${route.routeName}</strong>
                        <br>
                        <small class="text-muted">
                            <a href="#" onclick="showRouteDetail(${route.id})" class="text-decoration-none">
                                <i class="fas fa-info-circle me-1"></i>查看详情
                            </a>
                        </small>
                    </td>
                    <td>${getStationName(route.startStationId)}</td>
                    <td>${getStationName(route.endStationId)}</td>
                    <td>${route.totalDistance ? route.totalDistance + ' km' : '未设置'}</td>
                    <td>${formatDuration(route.estimatedDuration)}</td>
                    <td>${route.stationCount || 0} 站</td>
                    <td><span class="badge ${getStatusBadgeClass(route.status)}">${route.status}</span></td>
                    <td>${formatDateTime(route.createdAt)}</td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary me-1" onclick="showEditRouteModal(${route.id})" title="编辑">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn btn-sm btn-outline-danger" onclick="showDeleteModal(${route.id}, '${route.routeName}')" title="删除">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 获取车站名称
        function getStationName(stationId) {
            const station = stations.find(s => s.id === stationId);
            return station ? `${station.stationName} (${station.stationCode})` : '未知车站';
        }

        // 获取状态徽章样式
        function getStatusBadgeClass(status) {
            switch (status) {
                case '正常': return 'bg-success';
                case '停运': return 'bg-danger';
                case '维修': return 'bg-warning';
                default: return 'bg-secondary';
            }
        }

        // 格式化时长
        function formatDuration(minutes) {
            if (!minutes) return '未设置';
            const hours = Math.floor(minutes / 60);
            const mins = minutes % 60;
            return `${hours}小时${mins}分钟`;
        }

        // 显示添加线路模态框
        function showAddRouteModal() {
            document.getElementById('routeModalLabel').textContent = '添加线路';
            document.getElementById('routeForm').reset();
            document.getElementById('routeId').value = '';
            document.getElementById('routeStatus').value = '正常';
            routeStations = [];
            updateStationsTable();
        }

        // 显示编辑线路模态框
        async function showEditRouteModal(routeId) {
            try {
                const response = await fetch(`/api/routes/${routeId}`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取线路信息失败');
                }
                
                const route = await response.json();
                
                document.getElementById('routeModalLabel').textContent = '编辑线路';
                document.getElementById('routeId').value = route.id;
                document.getElementById('routeName').value = route.routeName;
                document.getElementById('startStation').value = route.startStationId;
                document.getElementById('endStation').value = route.endStationId;
                document.getElementById('totalDistance').value = route.totalDistance || '';
                document.getElementById('estimatedDuration').value = route.estimatedDuration || '';
                document.getElementById('routeStatus').value = route.status;
                
                // 加载经停站
                routeStations = route.stations || [];
                updateStationsTable();
                
                new bootstrap.Modal(document.getElementById('routeModal')).show();
            } catch (error) {
                console.error('获取线路信息失败:', error);
                showAlert('获取线路信息失败', 'danger');
            }
        }

        // 添加经停站
        function addStation() {
            const stationId = document.getElementById('stationSelect').value;
            const order = parseInt(document.getElementById('stationOrder').value);
            const distance = parseFloat(document.getElementById('stationDistance').value);
            
            if (!stationId || !order) {
                showAlert('请选择车站并输入站序', 'warning');
                return;
            }
            
            // 检查是否已存在
            if (routeStations.some(s => s.stationId === parseInt(stationId))) {
                showAlert('该车站已存在于经停站列表中', 'warning');
                return;
            }
            
            // 检查站序是否重复
            if (routeStations.some(s => s.order === order)) {
                showAlert('站序已存在，请使用不同的站序', 'warning');
                return;
            }
            
            const station = stations.find(s => s.id === parseInt(stationId));
            if (station) {
                routeStations.push({
                    stationId: parseInt(stationId),
                    stationName: station.stationName,
                    stationCode: station.stationCode,
                    order: order,
                    distance: distance || 0
                });
                
                // 按站序排序
                routeStations.sort((a, b) => a.order - b.order);
                updateStationsTable();
                
                // 清空输入
                document.getElementById('stationSelect').value = '';
                document.getElementById('stationOrder').value = '';
                document.getElementById('stationDistance').value = '';
            }
        }

        // 移除经停站
        function removeStation(index) {
            routeStations.splice(index, 1);
            updateStationsTable();
        }

        // 更新经停站表格
        function updateStationsTable() {
            const tbody = document.getElementById('stationsTableBody');
            
            if (routeStations.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4" class="text-center text-muted">暂无经停站</td></tr>';
                return;
            }
            
            tbody.innerHTML = routeStations.map((station, index) => `
                <tr>
                    <td>${station.order}</td>
                    <td>${station.stationName} (${station.stationCode})</td>
                    <td>${station.distance} km</td>
                    <td>
                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeStation(${index})">
                            <i class="fas fa-trash"></i>
                        </button>
                    </td>
                </tr>
            `).join('');
        }

        // 保存线路
        async function saveRoute() {
            try {
                const routeData = {
                    routeName: document.getElementById('routeName').value,
                    startStationId: parseInt(document.getElementById('startStation').value),
                    endStationId: parseInt(document.getElementById('endStation').value),
                    totalDistance: parseFloat(document.getElementById('totalDistance').value) || null,
                    estimatedDuration: parseInt(document.getElementById('estimatedDuration').value) || null,
                    status: document.getElementById('routeStatus').value,
                    stations: routeStations
                };

                // 验证必填字段
                if (!routeData.routeName || !routeData.startStationId || !routeData.endStationId) {
                    showAlert('请填写所有必填字段', 'warning');
                    return;
                }

                if (routeData.startStationId === routeData.endStationId) {
                    showAlert('起始站和终点站不能相同', 'warning');
                    return;
                }

                const routeId = document.getElementById('routeId').value;
                const url = routeId ? `/api/routes/${routeId}` : '/api/routes';
                const method = routeId ? 'PUT' : 'POST';

                const response = await fetch(url, {
                    method: method,
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                    body: JSON.stringify(routeData)
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '保存失败');
                }

                showAlert(routeId ? '线路更新成功' : '线路添加成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('routeModal')).hide();
                loadRoutes(currentPage);
            } catch (error) {
                console.error('保存线路失败:', error);
                showAlert(error.message || '保存线路失败', 'danger');
            }
        }

        // 显示线路详情
        async function showRouteDetail(routeId) {
            try {
                const response = await fetch(`/api/routes/${routeId}`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                
                if (!response.ok) {
                    throw new Error('获取线路详情失败');
                }
                
                const route = await response.json();
                
                const content = `
                    <div class="row">
                        <div class="col-md-6">
                            <h6>基本信息</h6>
                            <table class="table table-sm">
                                <tr><td>线路名称</td><td>${route.routeName}</td></tr>
                                <tr><td>起始站</td><td>${getStationName(route.startStationId)}</td></tr>
                                <tr><td>终点站</td><td>${getStationName(route.endStationId)}</td></tr>
                                <tr><td>总距离</td><td>${route.totalDistance ? route.totalDistance + ' km' : '未设置'}</td></tr>
                                <tr><td>预计时长</td><td>${formatDuration(route.estimatedDuration)}</td></tr>
                                <tr><td>状态</td><td><span class="badge ${getStatusBadgeClass(route.status)}">${route.status}</span></td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <h6>经停站信息</h6>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <thead>
                                        <tr><th>站序</th><th>车站</th><th>距离</th></tr>
                                    </thead>
                                    <tbody>
                                        ${route.stations && route.stations.length > 0 ? 
                                            route.stations.map(station => `
                                                <tr>
                                                    <td>${station.order}</td>
                                                    <td>${getStationName(station.stationId)}</td>
                                                    <td>${station.distance} km</td>
                                                </tr>
                                            `).join('') : 
                                            '<tr><td colspan="3" class="text-center text-muted">暂无经停站</td></tr>'
                                        }
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                `;
                
                document.getElementById('routeDetailContent').innerHTML = content;
                new bootstrap.Modal(document.getElementById('routeDetailModal')).show();
            } catch (error) {
                console.error('获取线路详情失败:', error);
                showAlert('获取线路详情失败', 'danger');
            }
        }

        // 显示删除模态框
        function showDeleteModal(routeId, routeName) {
            deleteRouteId = routeId;
            document.getElementById('deleteRouteName').textContent = routeName;
            new bootstrap.Modal(document.getElementById('deleteModal')).show();
        }

        // 确认删除
        async function confirmDelete() {
            try {
                const response = await fetch(`/api/routes/${deleteRouteId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });

                if (!response.ok) {
                    throw new Error('删除失败');
                }

                showAlert('线路删除成功', 'success');
                bootstrap.Modal.getInstance(document.getElementById('deleteModal')).hide();
                loadRoutes(currentPage);
            } catch (error) {
                console.error('删除线路失败:', error);
                showAlert('删除线路失败', 'danger');
            }
        }

        // 搜索线路
        function searchRoutes() {
            currentPage = 1;
            loadRoutes();
        }

        // 重置过滤器
        function resetFilters() {
            document.getElementById('searchRouteName').value = '';
            document.getElementById('searchStartStation').value = '';
            document.getElementById('searchEndStation').value = '';
            currentPage = 1;
            loadRoutes();
        }

        // 导出到CSV
        function exportToCSV() {
            const csvContent = generateCSVContent();
            downloadCSV(csvContent, 'routes.csv');
        }

        function generateCSVContent() {
            const headers = ['线路名称', '起始站', '终点站', '总距离', '预计时长', '经停站数', '状态', '创建时间'];
            let csv = headers.join(',') + '\n';
            
            const rows = document.querySelectorAll('#routesTableBody tr');
            rows.forEach(row => {
                const cells = row.querySelectorAll('td');
                if (cells.length > 1) {
                    const rowData = [
                        cells[0].textContent.trim().split('\n')[0],
                        cells[1].textContent.trim(),
                        cells[2].textContent.trim(),
                        cells[3].textContent.trim(),
                        cells[4].textContent.trim(),
                        cells[5].textContent.trim(),
                        cells[6].textContent.trim(),
                        cells[7].textContent.trim()
                    ];
                    csv += rowData.join(',') + '\n';
                }
            });
            
            return csv;
        }

        function downloadCSV(content, filename) {
            const blob = new Blob(['\ufeff' + content], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', filename);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 更新分页
        function updatePagination() {
            const pagination = document.getElementById('pagination');
            let paginationHTML = '';

            // 上一页
            paginationHTML += `
                <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadRoutes(${currentPage - 1})" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
            `;

            // 页码
            for (let i = 1; i <= totalPages; i++) {
                if (i === currentPage || i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                    paginationHTML += `
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" onclick="loadRoutes(${i})">${i}</a>
                        </li>
                    `;
                } else if (i === currentPage - 2 || i === currentPage + 2) {
                    paginationHTML += '<li class="page-item disabled"><a class="page-link">...</a></li>';
                }
            }

            // 下一页
            paginationHTML += `
                <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                    <a class="page-link" href="#" onclick="loadRoutes(${currentPage + 1})" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            `;

            pagination.innerHTML = paginationHTML;
        }

        // 显示加载状态
        function showLoading(show) {
            document.getElementById('loadingSpinner').style.display = show ? 'block' : 'none';
        }

        // 格式化日期时间
        function formatDateTime(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 显示提示信息
        function showAlert(message, type) {
            const alertDiv = document.createElement('div');
            alertDiv.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
            alertDiv.style.top = '20px';
            alertDiv.style.right = '20px';
            alertDiv.style.zIndex = '9999';
            alertDiv.innerHTML = `
                ${message}
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            `;
            document.body.appendChild(alertDiv);
            
            setTimeout(() => {
                if (alertDiv.parentNode) {
                    alertDiv.parentNode.removeChild(alertDiv);
                }
            }, 3000);
        }
    </script>
</body>
</html>
